package cn.doitedu;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import org.apache.hadoop.hive.ql.exec.UDF;
import org.apache.hadoop.io.BytesWritable;
import org.roaringbitmap.longlong.Roaring64Bitmap;

import java.io.IOException;
import java.util.Date;

/**
 * @Author: 深似海
 * @Site: <a href="www.51doit.com">多易教育</a>
 * @QQ: 657270652
 * @Date: 2024/4/26
 * @Desc: 学大数据，上多易教育
 *   求 给定任意日期 是否都活跃
 **/
public class BitmapIFDaysActiveUDF extends UDF {

    private static final Date INITIAL = DateUtil.parse("2000-01-01");

    public boolean evaluate(BytesWritable bitmapBytesWritable, String[] dates) throws IOException {

        // 先反序列化出bitmap对象
        Roaring64Bitmap bitmap = BitmapUtils.de(bitmapBytesWritable.getBytes());

        // 遍历输入的每一个日期
        boolean res = true;
        for (String date : dates) {
            // 将字符串日期，转成差值
            long between = DateUtil.between(INITIAL, DateUtil.parse(date), DateUnit.DAY);

            // 然后判断该差值在bitmap中是否存在
            if(! bitmap.contains(between)){
                res = false;
                break;
            }
        }

        return res;

    }
}
